<template>
  <app-list>
    <template #search>
      <Search :query="query" @change="getlistData()" @getExell="saveExell()" />
    </template>
    <template #action>
      <div class="order_action_tab">
        <div
          :style="activetype == 'danhang' ? 'color: var(--pcmain-color);' : ''"
          @click="changeactivetype('danhang')"
        >
          单行
        </div>
        <div
          style="margin-left: 16px"
          :style="activetype == 'zuhe' ? 'color: var(--pcmain-color);' : ''"
          @click="changeactivetype('zuhe')"
        >
          组合
        </div>
      </div>
    </template>
    <Table v-if="activetype == 'zuhe'" :list="listData" :task_type="task_type" :loading="tableloading" />
    <TableDh v-if="activetype == 'danhang'" :list="listData" :task_type="task_type" :loading="tableloading" />

    <div class="total_div">
      <div style="display: flex">
        <div class="total_item">
          <div>订单量:</div>
          <div>{{ analysis.page ? analysis.page.place_order_count : 0 }}</div>
        </div>
        <div class="total_item">
          <div>结算量:</div>
          <div>{{ analysis.page ? analysis.page.check_order_count : 0 }}</div>
        </div>
        <div class="total_item">
          <div>利润率:</div>
          <div>{{ analysis.page && analysis.page.profit_rate ? analysis.page.profit_rate : 0 }}</div>
        </div>
      </div>
    </div>

    <template #footerRight>
      <div style="height: 32px">
        <el-pagination
          @size-change="getlistData"
          @current-change="getlistData"
          v-model:current-page="query.page"
          v-model:page-size="query.page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        />
      </div>
    </template>
  </app-list>
</template>

<script setup>
const props = defineProps({
  task_type: String,
})
import { http } from '@/utils/http'
import { provide } from 'vue'
import Search from '../Search.vue'
import Table from '../Table.vue'
import TableDh from '../TableDh.vue'
import { ElMessage } from 'element-plus'

const activetype = ref('danhang')
const bc_types = ref([])
// const task_type = ref('_place_order')
const listData = ref([])
const tableloading = ref(true)

const analysis = ref({})
const usernames = ref([])
const rangeTime = ref('benzhou')
const timerange = ref([])
provide('bc_types', bc_types)
provide('activetype', activetype)
provide('usernames', usernames)
provide('rangeTime', rangeTime)
provide('timerange', timerange)

const query = ref({
  bc_type: '',
  task_type: '',
  is_win: 'all',
  user_name: 'all',
  check_status: 0,
  place_status: 2,
  page: 1,
  page_size: 20,
})

const total = ref(0)

const getlistData = () => {
  tableloading.value = true
  listData.value = []
  query.value.task_type = props.task_type
  let body = JSON.parse(JSON.stringify(query.value))
  if (body.bc_type == 'all') {
    delete body.bc_type
  }
  if (body.user_name == 'all') {
    delete body.user_name
  }
  if (body.is_win == 'all') {
    delete body.is_win
  }
  body.begin_time = timerange.value[0]
  body.end_time = timerange.value[1]

  if (props.task_type != null && props.task_type != undefined) {
    if (activetype.value == 'zuhe') {
      http.post('/order/order_list_bytask', body).then(res => {
        if (activetype.value == 'zuhe') {
          total.value = res.data.total
          listData.value = res.data.all_order_list
          analysis.value = res.data.analysis
          tableloading.value = false
        }
      })
    } else {
      http.post('/order/order_list', body).then(res => {
        if (activetype.value == 'danhang') {
          total.value = res.data.total
          listData.value = res.data.all_order_list
          analysis.value = res.data.analysis
          tableloading.value = false
        }
      })
    }
  }
}

provide('getlistData', getlistData)

const restructureList = list => {
  let copylist = JSON.parse(JSON.stringify(list))
  let a = []
  copylist.forEach(item => {
    let copyitem = JSON.parse(JSON.stringify(item))
    item.order_data = [
      {
        order_list: [copyitem],
        add_order_list: [],
      },
    ]
    item.bc_types = [item.bc_type]
    item.pk_odds_keys = [item.pk_odds_key]
    item.pk_odds_keys_ch = [item.pk_odds_key_ch]
    item.stakes = 38000
    a.push(item)
  })
  return a
}

const changeactivetype = value => {
  if (value != activetype.value) {
    activetype.value = value
    getlistData()
  }
}

const getbctypes = () => {
  http.get('/config/get_bc_type', { params: { page: 1, page_size: 999 } }).then(res => {
    bc_types.value = res.data.out_platform
  })
}

const saveExell = () => {
  if (total.value != 0) {
    let copyquery = JSON.parse(JSON.stringify(query.value))
    copyquery.page = 1
    copyquery.page_size = total.value
    if (copyquery.bc_type == 'all') {
      delete copyquery.bc_type
    }
    if (copyquery.user_name == 'all') {
      delete copyquery.user_name
    }
    if (copyquery.is_win == 'all') {
      delete copyquery.is_win
    }
    body.begin_time = timerange.value[0]
    body.end_time = timerange.value[1]
    if (activetype.value == 'zuhe') {
      http.post('/order/order_list_bytask', copyquery).then(res => {
        if (res.data.all_order_list.length > 0) {
          getExcel('zuhe', res.data.all_order_list)
        } else {
          ElMessage({
            message: '暂无可导出数据',
            type: 'warning',
          })
        }
      })
    } else {
      http.post('/order/order_list', copyquery).then(res => {
        if (res.data.all_order_list.length > 0) {
          getExcel('danhang', res.data.all_order_list)
        } else {
          ElMessage({
            message: '暂无可导出数据',
            type: 'warning',
          })
        }
      })
    }
  } else {
    ElMessage({
      message: '暂无可导出数据',
      type: 'warning',
    })
  }
}

const getExcel = async (type, data) => {
  let header1 = []
  let header2 = []
  if (type == 'danhang') {
    header1 = ['任务名称', '开赛时间', '联赛', '主队', '客队', '平台', '盘口', '下单总金额']
    header2 = [
      '下单时间',
      '下单(虚数)',
      '下单(实数)',
      '盈亏(虚数)',
      '盈亏(实数)',
      '盈亏状态',
      '交收状态',
      '结算状态',
      '平台单号',
      '下单账号',
      '操作员',
    ]
    if (props.task_type == '_copy_order_hand' || props.task_type == '_copy_order_auto') {
      header2.push('下单时比分')
    }
  } else {
    if (props.task_type == '_surebets_hand' || props.task_type == '_surebets_auto') {
      header1 = ['任务名称', '开赛时间', '联赛', '主队', '客队', '实数总金额', '盈亏状态', '利润率']
      header2 = [
        '平台',
        '盘口',
        '下单金额',
        '下单时间',
        '下单(虚数)',
        '下单(实数)',
        '盈亏(虚数)',
        '盈亏(实数)',
        '交收状态',
        '结算状态',
        '平台单号',
        '下单账号',
        '操作员',
      ]
    } else {
      header1 = ['任务名称', '开赛时间', '联赛', '主队', '客队']
      header2 = [
        '平台',
        '盘口',
        '下单金额',
        '下单时间',
        '下单(虚数)',
        '下单(实数)',
        '盈亏(虚数)',
        '盈亏(实数)',
        '盈亏状态',
        '交收状态',
        '结算状态',
        '平台单号',
        '下单账号',
        '操作员',
      ]
    }
  }

  let header = [...header1, ...header2]
  let datas = []
  if (type == 'danhang') {
    data.forEach(item => {
      let a = [
        item.task_name,
        item.created_at,
        item.league_name,
        item.home_name,
        item.away_name,
        bctypeLabel(item.bc_type),
        item.pk_odds_key_ch,
        item.total_amount,
      ]
      let is_settlement = '未标记'
      if (item.is_settlement == null || item.is_settlement == 0) {
        is_settlement = '未标记'
      } else if (item.is_settlement == 1) {
        is_settlement = '已标记'
      } else if (item.is_settlement == 2) {
        is_settlement = '已交收'
      }
      let b = [
        item.created_at,
        item.real_amount,
        item.total_amount,
        item.win_back,
        item.total_win_back,
        getprofitStatus(item.total_win_back, item.win_back),
        is_settlement,
        item.check_status == 0 ? '未结算' : '已结算',
        item.bet_id,
        item.user_name,
        item.uid,
      ]
      if (props.task_type == '_copy_order_hand' || props.task_type == '_copy_order_auto') {
        b.push(item.place_score)
      }

      let c = [...a, ...b]
      datas.push(c)
    })
  } else {
    if (props.task_type == '_surebets_hand' || props.task_type == '_surebets_auto') {
      data.forEach(item => {
        let a = [
          item.task_name,
          item.match_time,
          item.league_name,
          item.home_name,
          item.away_name,
          item.total_amount,
          getprofitStatus2(item.is_win),
          item.profit_rate,
        ]
        let a0 = ['', '', '', '', '', '', '', '']
        let isone = 0
        item.order_data.forEach((item2, index2) => {
          item2.order_list.forEach(item3 => {
            isone += 1
            let is_settlement = '未标记'
            if (item3.is_settlement == null || item3.is_settlement == 0) {
              is_settlement = '未标记'
            } else if (item3.is_settlement == 1) {
              is_settlement = '已标记'
            } else if (item3.is_settlement == 2) {
              is_settlement = '已交收'
            }
            let b = [
              bctypeLabel(item3.bc_type),
              item3.pk_odds_key_ch,
              item.stakes[index2],
              item3.created_at,
              item3.real_amount,
              item3.total_amount,
              item3.win_back,
              item3.total_win_back,
              is_settlement,
              item3.check_status == 0 ? '未结算' : '已结算',
              item3.bet_id,
              item3.user_name,
              item3.uid,
            ]
            let c = []
            if (isone == 1) {
              c = [...a, ...b]
            } else {
              c = [...a0, ...b]
            }
            datas.push(c)
          })
        })
      })
    } else {
      data.forEach(item => {
        let a = [item.task_name, item.match_time, item.league_name, item.home_name, item.away_name]
        let a0 = ['', '', '', '', '']
        let isone = 0
        item.order_data.forEach((item2, index2) => {
          item2.order_list.forEach(item3 => {
            isone += 1
            let is_settlement = '未标记'
            if (item3.is_settlement == null || item3.is_settlement == 0) {
              is_settlement = '未标记'
            } else if (item3.is_settlement == 1) {
              is_settlement = '已标记'
            } else if (item3.is_settlement == 2) {
              is_settlement = '已交收'
            }
            let b = [
              bctypeLabel(item3.bc_type),
              item3.pk_odds_key_ch,
              item.stakes[index2],
              item3.created_at,
              item3.real_amount,
              item3.total_amount,
              item3.win_back,
              item3.total_win_back,
              getprofitStatus2(item3.is_win),
              is_settlement,
              item3.check_status == 0 ? '未结算' : '已结算',
              item3.bet_id,
              item3.user_name,
              item3.uid,
            ]
            let c = []
            if (isone == 1) {
              c = [...a, ...b]
            } else {
              c = [...a0, ...b]
            }
            datas.push(c)
          })
        })
      })
    }
  }

  excels(header, datas)
}

const excels = async (header, datas) => {
  const worksheetData = [header, ...datas]
  let menus = [
    {
      label: '手动即时下单',
      value: 'jsch',
      task_type: '_place_order',
    },
    {
      label: '手动预约下单',
      value: 'yych',
      task_type: '_reservation_order',
    },
    {
      label: '机器人自动下单',
      value: 'sdds',
      task_type: '_robot_place_task',
    },
    {
      label: '手动跟单',
      value: 'sdgd',
      task_type: '_copy_order_hand',
    },
    {
      label: '自动跟单',
      value: 'zdgd',
      task_type: '_copy_order_auto',
    },
  ]
  let name = ''

  menus.forEach(item => {
    if (item.task_type == props.task_type) {
      name = item.label
    }
  })
  if (activetype.value == 'zuhe') {
    name += '_组合'
  } else {
    name += '_单行'
  }
  name += `_平台(${query.value.bc_type == 'all' ? '全部' : bctypeLabel(query.value.bc_type)})`
  name += `_${query.value.check_status == 0 ? '未结算' : '已结算'}`
  name += `_${query.value.place_status == 0 ? '下单失败' : '下单成功'}`
  name += `_输赢(${query.value.is_win == 'all' ? '全部' : iswinLabel(query.value.is_win)})`
  name += `_账号(${query.value.user_name == 'all' ? '全部' : query.value.user_name})`
  name += `_${query.value.begin_time}_${query.value.end_time}`
  // name += getCurrentTime()

  const result = await window.electron.dialogSave({ worksheetData: worksheetData, name: name })
  if (result == '取消保存') {
    ElMessage({
      message: result,
      type: 'warning',
    })
  } else if (result == '保存成功') {
    ElMessage({
      message: result,
      type: 'success',
    })
  } else {
    ElMessage.error(result)
  }
}

const bctypeLabel = value => {
  let name = ''
  bc_types.value.forEach(item => {
    if (item.bc_type == value) {
      name = item.name
    }
  })
  return name
}

const iswinLabel = value => {
  let a = ''
  if (value == 0) {
    a = '输'
  } else {
    a = '赢'
  }
  return a
}

const getprofitStatus2 = is_win => {
  if (is_win == 3) {
    return '走'
  } else if (is_win == 2) {
    return '盈'
  } else if (is_win == 1) {
    return '亏'
  } else {
    return '-'
  }
}

const getprofitStatus = (total_win_back, win_back) => {
  if (total_win_back == 0 && win_back == 0) {
    return '走'
  } else if (total_win_back > 0 || win_back > 0) {
    return '盈'
  } else if (total_win_back < 0 || win_back < 0) {
    return '亏'
  }
}

const getusername = () => {
  http.get(`/member/member_list?page=1&page_size=9999`).then(res => {
    usernames.value = res.data.list
  })
}

function getCurrentTime() {
  const now = new Date()

  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以要加1
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  return `${year}${month}${day}-${hours}${minutes}${seconds}`
}

// 格式化日期为 YYYY-MM-DD
const formatDate = date => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取本周的开始日期（周一）和结束日期（今天）
const getWeekRange = date => {
  const dayOfWeek = date.getDay() // 获取今天是周几
  const diffToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek // 计算到周一的差值
  const monday = new Date(date)
  monday.setDate(date.getDate() + diffToMonday) // 本周一

  return {
    start: formatDate(monday),
    end: formatDate(date), // 结束日期为今天
  }
}

onMounted(() => {
  let today = new Date()
  let a = getWeekRange(today)
  console.log(a)
  timerange.value = [a.start, a.end]

  query.value.begin_time = a.start
  query.value.end_time = a.end
  getbctypes()
  query.value.bc_type = 'all'
  getlistData()
  getusername()
})
</script>

<style lang="scss" scoped>
.order_action_tab {
  display: flex;
}
.order_action_tab div {
  cursor: pointer;
}

.total_div {
  height: 56px;
  margin-top: 8px;
  bottom: 0;
  background-color: rgba(248, 62, 62, 0.04);
  width: calc(100% + 32px);
  margin-left: -16px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.total_item {
  display: flex;
  margin-right: 40px;
  font-size: 16px;
}
.total_item div:nth-child(1) {
  width: 64px;
  height: 24px;
}
.total_item div:nth-child(2) {
  width: 88px;
  height: 24px;
  font-weight: 600;
}
::v-deep .app-list-body {
  justify-content: space-between;
}
</style>